import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user'
import {
  LoginFormData,
  LoginResponseData,
  userInfoResponseData,
} from '@/api/user/type.ts'
import type { UserState } from './types/type'
import { constantRoute } from '../../router/routers'

let useUserSrore = defineStore('User', {
  state: (): UserState => {
    return {
      token: localStorage.getItem('token'), // 用户唯一标识token
      menuRouters: constantRoute, //仓库存储菜单
      userName: '', // 用户名称
      avatar: '', //用户头像
    }
  },
  actions: {
    // 用户登录方法
    async useLogin(formData: LoginFormData) {
      const res: LoginResponseData = await reqLogin(formData)
      if (res.code == 200) {
        this.token = res.data as string
        localStorage.setItem('token', res.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data as string))
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      const res: userInfoResponseData = await reqUserInfo()
      if (res.code == 200) {
        this.userName = res.data.name
        this.avatar = res.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
    // 用户退出登录
    async userLogout() {
      const res: any = await reqLogOut()
      if (res.code == 200) {
        this.token = ''
        this.userName = ''
        this.avatar = ''
        localStorage.removeItem('token')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data.message))
      }
    },
  },
  getters: {},
})
export default useUserSrore
